const db = require('../models');
const { Op } = require('sequelize');

// 获取用户的所有健康提醒
exports.getAllReminders = async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 查询参数
    // 支持两种参数名称：member_id 或 memberId
    const memberId = req.query.memberId ? parseInt(req.query.memberId) : 
                     req.query.member_id ? parseInt(req.query.member_id) : null;
    
    const type = req.query.type || null;
    const status = req.query.status || null;
    const limit = req.query.limit ? parseInt(req.query.limit) : null;
    
    // 构建查询条件
    let where = { user_id: userId };
    
    if (memberId) {
      where.member_id = memberId;
    }
    
    if (type) {
      where.type = type;
    }
    
    if (status) {
      where.status = status;
    }
    
    // 查询提醒数据
    const reminders = await db.HealthReminder.findAll({
      where,
      limit,
      order: [['updatedAt', 'DESC']],
      include: [
        {
          model: db.FamilyMember,
          as: 'member',
          attributes: ['id', 'name', 'avatar', 'relationship', 'gender', 'birthday']
        }
      ]
    });
    
    // 处理返回的数据
    const formattedReminders = reminders.map(reminder => {
      const reminderData = reminder.toJSON();
      
      // 格式化数据
      return {
        id: reminderData.id,
        title: reminderData.title,
        content: reminderData.content,
        type: reminderData.type,
        time: reminderData.remind_time,
        date: reminderData.remind_date,
        repeatType: reminderData.repeat_type,
        repeatValue: reminderData.repeat_value,
        active: reminderData.status === 'active',
        status: reminderData.status,
        memberId: reminderData.member_id,
        memberName: reminderData.member ? reminderData.member.name : null,
        // 根据重复类型解析重复值
        days: reminderData.repeat_type === 'weekly' && reminderData.repeat_value ? 
          reminderData.repeat_value.split(',') : [],
        location: reminderData.type === 'checkup' ? reminderData.content : null
      };
    });
    
    return res.json({
      success: true,
      message: '获取健康提醒成功',
      data: {
        reminders: formattedReminders
      }
    });
    
  } catch (error) {
    console.error('获取健康提醒错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取健康提醒失败'
    });
  }
};

// 获取特定健康提醒详情
exports.getReminderById = async (req, res) => {
  try {
    const userId = req.user.id;
    const reminderId = req.params.id;
    
    const reminder = await db.HealthReminder.findOne({
      where: {
        id: reminderId,
        user_id: userId
      },
      include: [
        {
          model: db.FamilyMember,
          as: 'member',
          attributes: ['id', 'name', 'avatar', 'relationship', 'gender', 'birthday']
        }
      ]
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '未找到该健康提醒'
      });
    }
    
    const reminderData = reminder.toJSON();
    
    return res.json({
      success: true,
      message: '获取健康提醒详情成功',
      data: {
        reminder: {
          id: reminderData.id,
          title: reminderData.title,
          content: reminderData.content,
          type: reminderData.type,
          time: reminderData.remind_time,
          date: reminderData.remind_date,
          repeatType: reminderData.repeat_type,
          repeatValue: reminderData.repeat_value,
          status: reminderData.status,
          // HealthReminder模型中没有is_enabled字段
          memberId: reminderData.member_id,
          member: reminderData.member
        }
      }
    });
    
  } catch (error) {
    console.error('获取健康提醒详情错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，获取健康提醒详情失败'
    });
  }
};

// 创建新的健康提醒
exports.createReminder = async (req, res) => {
  try {
    const userId = req.user.id;
    const {
      member_id, title, content, type, remind_time, remind_date,
      repeat_type, repeat_value
    } = req.body;
    
    // 验证必填字段
    if (!member_id || !title || !remind_time || !type) {
      return res.status(400).json({
        success: false,
        message: '家庭成员ID、提醒标题、提醒时间和提醒类型为必填字段'
      });
    }
    
    // 验证类型是否有效
    const validTypes = ['medication', 'checkup', 'exercise', 'diet', 'other'];
    if (type && !validTypes.includes(type)) {
      return res.status(400).json({
        success: false,
        message: `提醒类型 "${type}" 无效，有效类型: ${validTypes.join(', ')}`
      });
    }
    
    // 验证成员是否存在
    const member = await db.FamilyMember.findOne({
      where: {
        id: member_id,
        user_id: userId
      }
    });
    
    if (!member) {
      // 尝试不带用户ID查询成员
      const anyMember = await db.FamilyMember.findOne({
        where: {
          id: member_id
        }
      });
      
      return res.status(404).json({
        success: false,
        message: '未找到该家庭成员'
      });
    }
    
    // 创建健康提醒
    const newReminder = await db.HealthReminder.create({
      user_id: userId,
      member_id,
      title,
      content: content || null,
      type,
      remind_time,
      remind_date: remind_date || null,
      repeat_type: repeat_type || 'once',
      repeat_value: repeat_value || null,
      status: 'active',
      last_reminded_at: new Date()
    });
    
    return res.status(201).json({
      success: true,
      message: '创建健康提醒成功',
      data: {
        reminder: {
          id: newReminder.id,
          title: newReminder.title,
          type: newReminder.type,
          status: newReminder.status
        }
      }
    });
    
  } catch (error) {
    console.error('创建健康提醒错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，创建健康提醒失败'
    });
  }
};

// 更新健康提醒信息
exports.updateReminder = async (req, res) => {
  try {
    const userId = req.user.id;
    const reminderId = req.params.id;
    const updateData = req.body;
    
    // 查找提醒
    const reminder = await db.HealthReminder.findOne({
      where: {
        id: reminderId,
        user_id: userId
      }
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '未找到该健康提醒'
      });
    }
    
    // 如果要更新成员ID，验证该成员是否存在
    if (updateData.member_id) {
      const member = await db.FamilyMember.findOne({
        where: {
          id: updateData.member_id,
          user_id: userId
        }
      });
      
      if (!member) {
        return res.status(404).json({
          success: false,
          message: '未找到该家庭成员'
        });
      }
    }
    
    // 更新提醒信息
    const updateFields = {
      title: updateData.title !== undefined ? updateData.title : reminder.title,
      content: updateData.content !== undefined ? updateData.content : reminder.content,
      type: updateData.type !== undefined ? updateData.type : reminder.type,
      remind_time: updateData.remind_time !== undefined ? updateData.remind_time : reminder.remind_time,
      remind_date: updateData.remind_date !== undefined ? updateData.remind_date : reminder.remind_date,
      repeat_type: updateData.repeat_type !== undefined ? updateData.repeat_type : reminder.repeat_type,
      repeat_value: updateData.repeat_value !== undefined ? updateData.repeat_value : reminder.repeat_value,
      member_id: updateData.member_id !== undefined ? updateData.member_id : reminder.member_id
    };
    
    // 处理状态和启用状态
    if (updateData.status !== undefined) {
      updateFields.status = updateData.status;
    }
    
    await reminder.update(updateFields);
    
    return res.json({
      success: true,
      message: '更新健康提醒成功',
      data: {
        id: reminder.id
      }
    });
    
  } catch (error) {
    console.error('更新健康提醒错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，更新健康提醒失败'
    });
  }
};

// 删除健康提醒
exports.deleteReminder = async (req, res) => {
  try {
    const userId = req.user.id;
    const reminderId = req.params.id;
    
    // 查找提醒
    const reminder = await db.HealthReminder.findOne({
      where: {
        id: reminderId,
        user_id: userId
      }
    });
    
    if (!reminder) {
      return res.status(404).json({
        success: false,
        message: '未找到该健康提醒'
      });
    }
    
    // 删除提醒
    await reminder.destroy();
    
    return res.json({
      success: true,
      message: '删除健康提醒成功'
    });
    
  } catch (error) {
    console.error('删除健康提醒错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误，删除健康提醒失败'
    });
  }
}; 